const mysql = require('mysql2/promise');

async function main() {
    const args = process.argv.slice(2);
    let characterId = 2010;
    for (let i = 0; i < args.length; i++) {
        if (args[i] === '--id' && args[i + 1]) {
            characterId = parseInt(args[i + 1], 10);
        }
    }
    if (!characterId || Number.isNaN(characterId)) {
        console.error('无效的参数: 请使用 --id <characterId>');
        process.exit(1);
    }

    const config = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
        multipleStatements: true,
        timezone: '+08:00'
    };

    let connection;
    try {
        connection = await mysql.createConnection(config);
        console.log('✅ 已连接数据库');

        // 查询1级所需经验
        const [rows] = await connection.execute(
            'SELECT experience FROM level_experience WHERE level = ? LIMIT 1',
            [1]
        );
        const expNeed = rows && rows[0] && rows[0].experience ? Number(rows[0].experience) : 1000;

        // 重置角色等级与经验（exp 表示升级所需剩余经验）
        const [result] = await connection.execute(
            'UPDATE characters SET lvl = ?, exp = ?, trans = 0 WHERE id = ? LIMIT 1',
            [1, expNeed, characterId]
        );

        console.log(`✅ 已重置角色 ${characterId} 等级为1，exp=${expNeed}，影响行数=${result.affectedRows}`);

        // 可选：清理训练记录状态，避免卡在已完成状态
        await connection.execute(
            'UPDATE character_training SET is_training = 0, training_status = 0, training_hours = 0, pending_exp = 0 WHERE character_id = ? LIMIT 1',
            [characterId]
        );
        console.log('✅ 已重置训练状态');

        await connection.end();
    } catch (err) {
        console.error('❌ 重置失败:', err.message);
        try { if (connection) await connection.end(); } catch (_) { }
        process.exit(1);
    }
}

if (require.main === module) {
    main();
}


